package com.agencia.socketserver;

import java.io.IOException;
import java.net.ServerSocket;

import javax.servlet.ServletConfig;
//import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.agencia.constant.Constants;

/**
 * Servlet implementation class AgenciaSocketServer
 */
public class AgenciaSocketServer extends HttpServlet implements Runnable {
	private static final long serialVersionUID = 1L;
	private static errors logSys = errors.getInstance();   
	private boolean listening = true;
    
    Thread agenciaThread = new Thread(this);

	public AgenciaSocketServer() {
		super();
		agenciaThread.start();
	}
	
	public void run() {
		ServerSocket serverSocket = null;
	    ServletConfig config = super.getServletConfig();    
	        

	    try {
	        //Se pasa la configuracion del Servlet
	        errors.setServletConfig(config);
	        
	        ConfigParam configParam = ConfigParam.getInstance();
	        configParam.cargarParametrosServlets(config);
		
			serverSocket = new ServerSocket(Integer.parseInt(Constants.getGlobalParam().get("port")));	
			//serverSocket.setSoTimeout(10000);
				
		} catch (IOException e) {
        	logSys.writeError(Constants.getLoginerror() + e.getMessage());
		
		} 
       
	    while(listening){
            try {
      			logSys.writeError("Se invoca el Thread Port: " + Constants.getGlobalParam().get("port"));
      			new AgenciaMultiServerThread(serverSocket.accept()).start();
      			
      		} catch (IOException e) {
    			logSys.writeError(Constants.getLoginerror() + " Port: " + Constants.getGlobalParam().get("port")+ " " + e.getMessage());
    			
    		}	
	    }
	}
}
